/////////////////////////////////////////////////////////////////////////

package sheep.view;

/////////////////////////////////////////////////////////////////////////

import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import java.util.LinkedList;
import java.util.LinkedList;
import javax.beans.binding.BindingContext;
import javax.beans.binding.CompositeBindingDescription;
import javax.imageio.ImageIO;
import javax.swing.AbstractListModel;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JPanel;


import javax.swing.binding.SwingBindingSupport;
import javax.swing.filechooser.FileFilter;
import org.jdesktop.fuse.ResourceInjector;
import org.jdesktop.swingx.JXList;
import org.jdesktop.swingx.JXPanel;
import org.jdesktop.swingx.StackLayout;
import org.jdesktop.swingx.VerticalLayout;

import sheep.controller.Workspace;
import sheep.model.Project;
import sheep.model.Task;
import sheep.model.Worker;
import sheep.model.graph.Graph;
import sheep.utils.fileio.Bundles;
import sheep.view.Component.ActionButton;
import sheep.view.Component.ProjectListCellRenderer;
import sheep.view.Component.RoundedPanel;
import sheep.view.Component.SheepScrollbarUI;
import sheep.view.utils.swingx.DropShadowPanel;

// Panneau de projet principal
class ProjectSelectPanel extends JPanel {
  
  /////////////////////////////////////////////////////////////////////////

    // Zoom de raccourccis

    Workspace workSpace;    
  
    private javax.swing.JPanel mainPanel;
    private javax.swing.JButton projectLeftAddButton;
    private javax.swing.JButton projectLeftEditButton;
    private javax.swing.JPanel projectLeftPanel;
    private javax.swing.JButton projectLeftRemButton;
    private javax.swing.JLabel projectOpLabel;
    private javax.swing.JButton projectOpenButton;
    private javax.swing.JPanel projectPanel;
    private javax.swing.JButton projectResumeButton;
    private javax.swing.JScrollPane projectScrollPane;
    private javax.swing.JPanel projectSouthCenterPanel;
    private javax.swing.JButton projectSouthGantButton;
    private javax.swing.JButton projectSouthGrapheButton;
    private javax.swing.JPanel projectSouthLeftPanel;
    private javax.swing.JPanel projectSouthPanel;
    private javax.swing.JPanel projectSouthRightPanel;
    private javax.swing.JButton projectSouthUsersButton;
    private org.jdesktop.swingx.JXList projectjXList;
    private javax.swing.JLabel titleLabel;
    private javax.swing.JPanel titlePanel; 

    private UserChooserTopPanel userChooserTopPanel; 

    private Project project;
    
    private static int i =0;
    ////////////////////////////////////////////////////////////////////////////
    // THEME SPECIFIC FIELDS
    ////////////////////////////////////////////////////////////////////////////




    
    public void refresh(){
      //        projectjXList.setCellRenderer(new ProjectListCellRenderer());
      //  projectjXList.setPrototypeCellValue("xxx");
     //   SwingBindingSupport.register();
        BindingContext context = new BindingContext();
        context.addDescription(new CompositeBindingDescription(workSpace.getProjectList(), projectjXList, "elements"));
        context.bind();
        
      projectjXList.repaint();
      repaint();
    }
    
    
    ProjectSelectPanel(Workspace workSpace) {
        // Charger les attributs pecedents depuis le fichier de conf
        ResourceInjector.get().inject(this);
        this.workSpace =workSpace;
        
        // On s'oocupe de l'arriere plan
        setOpaque(false);
        // Layout
        setLayout(new BorderLayout());

        // Ajout des composants
        JPanel centerPanel = new JPanel(new BorderLayout());
        centerPanel.setOpaque(false);
        centerPanel.add(BorderLayout.CENTER, buildProjectInfoPanel());

        
        userChooserTopPanel = new UserChooserTopPanel(this.workSpace);   
        JXPanel centerSatckPanel = new JXPanel(new StackLayout());
        centerSatckPanel.setOpaque(false);
        centerSatckPanel. add(centerPanel, StackLayout.TOP);
        userChooserTopPanel.setVisible2(false);
        centerSatckPanel.add(userChooserTopPanel,StackLayout.TOP );    
        add(centerSatckPanel, BorderLayout.CENTER);

    
    }

    /////////////////////////////////////////////////////////////////////////

    // création de la zone operation en haut
        private JPanel buildProjectInfoPanel() {
        // Nouveau panel
        JPanel taskPanel = new JPanel(new BorderLayout());
        taskPanel.setOpaque(false);
        taskPanel.setBorder(BorderFactory.createEmptyBorder(10,1,10,1));
        // Ajout d'un titre floutés
        taskPanel.add(BorderLayout.NORTH, new BackgroundMenuTitle(
                Bundles.getMessage(getClass(), "TXT_NewProjet")));
        
        // Sous panel
        
        ////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////
        
        ////////////////////////
        // 1ERE PAGE

        mainPanel = new DropShadowPanel();
        titlePanel = new javax.swing.JPanel();
        titleLabel = new javax.swing.JLabel();
        projectPanel = new javax.swing.JPanel();
        projectSouthPanel = new javax.swing.JPanel();
        projectSouthLeftPanel = new javax.swing.JPanel();
        projectOpenButton = new ActionButton();
        projectSouthCenterPanel = new javax.swing.JPanel();
        projectSouthGrapheButton = new ActionButton();
        projectSouthGantButton = new ActionButton();
        projectSouthUsersButton = new ActionButton();
        projectSouthRightPanel = new javax.swing.JPanel();
        projectResumeButton = new ActionButton();
        projectLeftPanel = new javax.swing.JPanel();
        projectOpLabel = new javax.swing.JLabel();
        projectLeftAddButton = new ActionButton();
        projectLeftRemButton = new ActionButton();
        projectLeftEditButton = new ActionButton();
        projectScrollPane = new javax.swing.JScrollPane();
        projectjXList = new ProjectList();


    mainPanel.setOpaque(false);
    BorderLayout layout = new BorderLayout();
    layout.setVgap(10);
    mainPanel.setLayout(layout);

    titlePanel.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 10, 1));
    titlePanel.setOpaque(false);
    titlePanel.setPreferredSize(new java.awt.Dimension(258, 35));
    titlePanel.setLayout(new java.awt.BorderLayout());

    titleLabel.setFont(new java.awt.Font("Times New Roman", 1, 24));
    titleLabel.setForeground(new java.awt.Color(255, 255, 255));
    titleLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    titleLabel.setText("CHOISIR PROJECT");
    titlePanel.add(titleLabel, java.awt.BorderLayout.CENTER);

    mainPanel.add(titlePanel,BorderLayout.NORTH);

    projectPanel.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 10, 1));
    projectPanel.setOpaque(false);
    projectPanel.setPreferredSize(new java.awt.Dimension(150, 100));
    BorderLayout layout1 = new BorderLayout();
    layout1.setVgap(10);
    layout1.setHgap(10);
    projectPanel.setLayout(layout1);

    projectSouthPanel.setOpaque(false);
    projectSouthPanel.setPreferredSize(new java.awt.Dimension(100, 31));
    projectSouthPanel.setLayout(new java.awt.BorderLayout());

    projectSouthLeftPanel.setOpaque(false);

    projectOpenButton.setText("Ouvrir");
    projectOpenButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
 
      }
    });
    projectSouthLeftPanel.add(projectOpenButton);

    //projectSouthPanel.add(projectSouthLeftPanel, java.awt.BorderLayout.WEST);

    projectSouthCenterPanel.setOpaque(false);

    projectSouthGrapheButton.setText("Graphe");
    projectSouthGrapheButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        TransitionManager.showProjectGraphEdit();
      }
    });    
    
    projectSouthCenterPanel.add(projectSouthGrapheButton);

    projectSouthGantButton.setText("Gant");
    projectSouthGantButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        TransitionManager.showGanttEdit();
      }
    }); 
    
    projectSouthCenterPanel.add(projectSouthGantButton);

    projectSouthUsersButton.setText("Participants");
    projectSouthUsersButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        TransitionManager.showUser();
      }
    });        
   
    projectSouthCenterPanel.add(projectSouthUsersButton);

    projectSouthPanel.add(projectSouthCenterPanel, java.awt.BorderLayout.CENTER);

    projectSouthRightPanel.setOpaque(false);

    projectResumeButton.setText("Resumé");
    projectResumeButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
      }
    });
    projectSouthRightPanel.add(projectResumeButton);

    //projectSouthPanel.add(projectSouthRightPanel, java.awt.BorderLayout.EAST);

    projectPanel.add(projectSouthPanel, java.awt.BorderLayout.SOUTH);

    projectLeftPanel.setOpaque(false);
    projectLeftPanel.setPreferredSize(new java.awt.Dimension(100, 31));
    projectLeftPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10));
    projectLeftPanel.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER, 5, 10));

    projectOpLabel.setFont(new java.awt.Font("Times New Roman", 1, 14));
    projectOpLabel.setForeground(new java.awt.Color(255, 255, 255));
    projectOpLabel.setText("Opérations :");
    projectOpLabel.setPreferredSize(new java.awt.Dimension(100, 17));
    projectLeftPanel.add(projectOpLabel);

    projectLeftAddButton.setText("+");
    projectLeftAddButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {

        Project project = new Project("Nouveau Projet " + i++, workSpace);
        project.addGraph(null);
        workSpace.getProjectList().add(project);
        workSpace.setCurrentProject(project);
        workSpace.setCurrentTask(project);
        

        
    /*    projectjXList.setModel(new javax.swing.AbstractListModel() {
          LinkedList<Task> projectList = workSpace.getProjectList();
          public int getSize() { return projectList.size(); }
          public Object getElementAt(int i) { return projectList.get(i).getName(); }
        });
    */
        refresh();
        projectjXList.setSelectedIndex(workSpace.getProjectList().size()-1);
        
      }
    });
    projectLeftPanel.add(projectLeftAddButton);

    projectLeftRemButton.setText("-");
    projectLeftRemButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
              
        workSpace.getProjectList().remove(((Task)projectjXList.getSelectedValue()));
        if (workSpace.getProjectList().size()>0){
          projectjXList.setSelectedIndex(workSpace.getProjectList().size()-1);
          workSpace.setCurrentProject( ((Task)projectjXList.getSelectedValue()));
          workSpace.setCurrentTask( ((Task)projectjXList.getSelectedValue()));
        }else{
          workSpace.setCurrentProject(null);
          workSpace.setCurrentTask(null);
        }
        refresh();
        if (workSpace.getProjectList().size()>0)
        projectjXList.setSelectedIndex(workSpace.getProjectList().size()-1);
      }
      
    });
    projectLeftPanel.add(projectLeftRemButton);

    projectLeftEditButton.setText("Editer");
    projectLeftEditButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        if (workSpace.getCurrentProject() != null)
          TransitionManager.showProjectEdit();
      }
    });
    
    projectLeftPanel.add(projectLeftEditButton);

    projectPanel.add(projectLeftPanel, java.awt.BorderLayout.WEST);

    projectScrollPane.setBorder(null);
    projectScrollPane.setOpaque(false);
    
    projectjXList.setCellRenderer(new ProjectListCellRenderer());
    projectjXList.setPrototypeCellValue("xxx");
    SwingBindingSupport.register();
    BindingContext context = new BindingContext();
    context.addDescription(new CompositeBindingDescription(workSpace.getProjectList(), projectjXList, "elements"));
    context.bind();
        
    projectjXList.setOpaque(false);
    projectjXList.addMouseListener(new MouseListener(){
      int i;
      public void mouseClicked(MouseEvent e) {

      }

      public void mousePressed(MouseEvent e) {
        i = projectjXList.getSelectedIndex();
        if (projectjXList.getSelectedIndex()>=0){
        workSpace.setCurrentProject(workSpace.getProjectList().get(projectjXList.getSelectedIndex()));
        workSpace.setCurrentTask(workSpace.getProjectList().get(projectjXList.getSelectedIndex()));
        refresh();
        }
      }

      public void mouseReleased(MouseEvent e) {
        projectjXList.setSelectedIndex(i);
      }

      public void mouseEntered(MouseEvent e) {
      }

      public void mouseExited(MouseEvent e) {
      }
    
    });
    projectScrollPane.getVerticalScrollBar().setUI(new SheepScrollbarUI());
    projectScrollPane.setViewportView(projectjXList);

    projectPanel.add(new RoundedPanel(projectScrollPane), BorderLayout.CENTER);

    mainPanel.add(new RoundedPanel(projectPanel),BorderLayout.CENTER);
     

        ////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////
              
        //Ajout au panel principal
        taskPanel.add(BorderLayout.CENTER, mainPanel);
              
      
        
        // Création de marge
        taskPanel.add(BorderLayout.WEST, Box.createHorizontalStrut(60));
        taskPanel.add(BorderLayout.EAST, Box.createHorizontalStrut(60));

        return taskPanel;
    }
        

    private static final class ProjectList extends JXList {
    @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            int height = getHeight();
            int prefHeight = getPreferredSize().height;
            if (prefHeight < height) {
                int modelSize = getModel().getSize();
                int cellHeight = getFixedCellHeight();
                int startRow = modelSize / 2 * 2;
                if (startRow < modelSize) {
                    startRow += 2;
                }
                int y = startRow * cellHeight;
                int w = getWidth();
                g.setColor(ProjectListCellRenderer.STRIPE_COLOR);
                while (y < height) {
                    g.fillRect(0, y, w, cellHeight);
                    y += cellHeight + cellHeight;
                }
            }
        }
    }
            
    /////////////////////////////////////////////////////////////////////////

    public static class UserListModel extends AbstractListModel{
      Workspace workspace;
      public UserListModel(Workspace workspace){
        this.workspace = workspace;
      }
      
          @Override
          public int getSize() { return workspace.getCurrentProject().getWorkersList().size(); }
          @Override
          public Object getElementAt(int i) { return workspace.getCurrentProject().getWorkersList().get(i).getFirstName() + " "+
                  workspace.getCurrentProject().getWorkersList().get(i).getLastName(); }
          public Worker getWorker(int i) { return workspace.getCurrentProject().getWorkersList().get(i);}
          
          public void deleteWorker ( Worker worker){
            workspace.getCurrentProject().getWorkersList().remove(worker);
          }
      
    }
    
     public static class ManagerListModel extends AbstractListModel{
      Workspace workspace;
      public ManagerListModel(Workspace workspace){
        this.workspace = workspace;
      }
      
          @Override
          public int getSize() { return workspace.getCurrentProject().getManagers().size(); }
          @Override
          public Object getElementAt(int i) { return workspace.getCurrentProject().getManagers().get(i).getFirstName() + " "+
                  workspace.getCurrentProject().getManagers().get(i).getLastName(); }
          public Worker getWorker(int i) { return workspace.getCurrentProject().getManagers().get(i);}
          
          public void deleteWorker ( Worker worker){
            workspace.getCurrentProject().getManagers().remove(worker);
          }      
    }
        
 
    public static class UserTaskListModel extends AbstractListModel{
      Workspace workspace;
      public UserTaskListModel(Workspace workspace){
        this.workspace = workspace;
      }
      
          @Override
          public int getSize() { return workspace.getCurrentTask().getWorkersList().size(); }
          @Override
          public Object getElementAt(int i) { return workspace.getCurrentTask().getWorkersList().get(i).getFirstName() + " "+
                  workspace.getCurrentTask().getWorkersList().get(i).getLastName(); }
          public Worker getWorker(int i) { return workspace.getCurrentTask().getWorkersList().get(i);}
          
          public void deleteWorker ( Worker worker){
            workspace.getCurrentTask().getWorkersList().remove(worker);
          } 
    }       
        
    public class MonFiltre extends FileFilter {

    String []lesSuffixes;
    String  laDescription;

   public MonFiltre(String []lesSuffixes, String laDescription){
        this.lesSuffixes = lesSuffixes;
        this.laDescription = laDescription;
   }

   boolean appartient( String suffixe ){
      for( int i = 0; i<lesSuffixes.length; ++i){
          if(suffixe.equals(lesSuffixes[i])) return true;
      }
      return false;
   }

   public boolean accept(File f) {
     if (f.isDirectory()) {
         return true;
     }
     String suffixe = null;
     String s = f.getName();
     int i = s.lastIndexOf('.');
    if (i > 0 &&  i < s.length() - 1) {
         suffixe = s.substring(i+1).toLowerCase();
     }
     return suffixe != null && appartient(suffixe);
   }

   // la description du filtre
   public String getDescription() {
       return laDescription;
   }
  }

  public static class ResizingImage {

  static BufferedImage imgNew = null;


  public static BufferedImage resize(int newWidth, int newHeight, String imgPath) {

    try {
      File imgFile = new File(imgPath);
      BufferedImage imgOld = ImageIO.read(imgFile);
      imgNew = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);

      /// Resizing of the old image ////////////////////////
      Graphics2D g = (Graphics2D) imgNew.getGraphics();
      g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
      g.drawImage(imgOld, 0, 0, newWidth, newHeight, null);
      g.dispose();
      /////////////////////////////////////////////////////

    } catch (IOException e) {
      e.printStackTrace();
    }

  return imgNew;
  }

  public static BufferedImage resize(int newWidth, int newHeight, String imgPath, String strg) {

  imgNew = resize(newWidth, newHeight, imgPath);

    try {
      ImageIO.write(imgNew, "jpeg", new File(strg));
    } catch (IOException e) {
      e.printStackTrace();
    }

  return imgNew;
  }

} 

    
}

/////////////////////////////////////////////////////////////////////////
